package org.ymy2;

import org.apache.hadoop.hive.ql.exec.UDF;

import java.text.SimpleDateFormat;
import java.util.Date;

public class CalcUDF extends UDF {

    // 记录上一次访问信息
    private String[] lastLine = new String[1];

    // 记录上次一次访问时间
    private String lastTime = null;

    // 符合规则的累加值
    private long sumValue = 0;

    // 清除下一行的累加值
    private boolean isCleanInNext = false;

    public Long evaluate(String currentTime, String[] currentLine) throws Exception {
        // 首次进入udf
        if (lastTime == null) {

            lastTime = currentTime;
            for (int i = 0; i < currentLine.length; i++) {
                lastLine[i] = currentLine[i];
            }

            return 0L;
        } else {
            // 同一个用户执行逻辑
            if (currentLine[0].equals(lastLine[0])) {
                if (isCleanInNext == true){
                    isCleanInNext = false;
                    lastTime = currentTime;
                    for (int i = 0; i < currentLine.length; i++) {
                        lastLine[i] = currentLine[i];
                    }
                    return 0L;
                }
                SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy/MM/dd hh:mm");
                Date fromDate = simpleFormat.parse(lastTime);
                Date toDate = simpleFormat.parse(currentTime);
                long from = fromDate.getTime();
                long to = toDate.getTime();

                // 分钟差
                long userTimeL = (to - from) / (1000 * 60);
                Long useTime = new Long(userTimeL);
                sumValue += userTimeL;
                // 如果是当前组的累加值超过30，打上给下一行数据耗时清零的标识
                if (sumValue > 30){
                    isCleanInNext = true;
                    sumValue = 0;
                }

                lastTime = currentTime;

                for (int i = 0; i < currentLine.length; i++) {
                    lastLine[i] = currentLine[i];
                }
                return useTime;
            } else { // 另一个用户
                isCleanInNext = false;
                sumValue = 0;
                lastTime = currentTime;
                for (int i = 0; i < currentLine.length; i++) {
                    lastLine[i] = currentLine[i];
                }
                return 0L;
            }
        }
    }
}
